const router = require('koa-router')(); //注意：引入的方式
const db = require('../utils/database.js')

router.prefix('/table')

router.get('/', ctx => {
	ctx.body = "table--index";
})


// 查询 分页 搜索 排序
router.get('/list', async ctx => {
	const { order, by, page = 0, pageSize = 20, query, query1, query2, query3 } = ctx.request
		.query // request可省略
	let sort = {},
		where = {}
	if (by) {
		sort[by] = order // by是条件 order是-1或1
	}
	if (query) { // 卓型
		where.cut = { $regex: new RegExp(query) }
	}
	if (query1) { // 桌位
		where.position = { $regex: new RegExp(query1) }
	}
	if (query2) { // 是否正在使用
		where.state = { $regex: new RegExp(query2) }
	}
	if (query3 == 'true') { // 启用状态
		where.status = true
	} else if (query3 == 'false') {
		where.status = false
	}
	//总条数
	const total = await db.total('table', where)
	const data = await db.find('table', { where, sort, skip: page * pageSize, limit: pageSize })
	ctx.body = { success: true, code: 20000, message: "数据查询成功", data, total }
})

// 桌号查重
router.get('/get-number', async ctx => {
	const { number } = ctx.request.query // request可省略
	const data = await db.findOne('table', { number })
	ctx.body = { success: true, code: 20000, message: "数据查询成功", data }
})


// 新增
router.post('/save', async ctx => {
	// status启用状态 是否启用   state台桌状态 是否正在使用
	const { cut, number, position, state, status, } = ctx.request.body;
	const data = await db.insert('table', { cut, number, position, state, status, time: Date.now() })
	ctx.body = { success: true, code: 20000, message: "数据新增成功", data }
})

// 修改
router.post('/modify', async ctx => {
	const { _id, cut, number, position, state, status } = ctx.request.body
	const data = await db.update('table', { _id }, {
		cut,
		number,
		position,
		state,
		status,
		time: Date.now()
	})
	ctx.body = { success: true, code: 20000, message: "数据修改成功", data }
})

// 删除
router.get('/delete', async ctx => {
	const { _id } = ctx.request.query
	const data = await db.delete('table', { _id })
	ctx.body = { success: true, code: 20000, message: "数据删除成功", data }
})

module.exports = router
